#include "Session.h"
#include <iostream>

Session::Session(std::shared_ptr<tcp::socket> socket) : m_socket(socket) 
{
    if (m_name.empty())
    {
        auto port = m_socket->remote_endpoint().port();
        m_name = m_socket->remote_endpoint().address().to_string() + ":" + std::to_string(port);

        std::cout << "new session created, name: " << m_name << std::endl;
    }
}
Session::~Session()
{
    Stop();
}

void Session::Start() 
{
    std::cout << "Session::Start()" << std::endl;
    if (m_isRunning)
    {
        return;
    }
    m_isRunning = true;

    Recv();                     // 启动监听数据

    // Send("welcome !!!");
}

void Session::Stop()
{
    m_isRunning = false;
    m_socket->close();
}

std::string Session::GetName()
{
    return m_name;
}

void Session::SetCloseCallback(const SessionCloseCallback& callback)
{
    m_closeCallback = callback;
}

void Session::OnCloseSession()
{
    if (m_closeCallback != nullptr)
    {
        m_closeCallback(m_name);
    }
}

void Session::Recv()
{
    if (!m_isRunning)
    {
        std::cout << "Session is not running. do not recv msg" << std::endl;
        return;
    }

    // std::cout << "Session::Recv()" << std::endl;

    memset(m_data, 0, MAX_LENGTH);          // 接收前清空数据
    m_socket->async_read_some(boost::asio::buffer(m_data, MAX_LENGTH),
        [self = shared_from_this()](const boost::system::error_code& error, std::size_t bytes_transferred) {
            if (!error)
            {
                std::cout << "==> Received from client. buf_size: " << bytes_transferred << std::endl;
                self->OnRecv(self->m_data, bytes_transferred);
            }
            else
            {
                std::cerr << "Error receiving from client: " << error.message() << std::endl;
                if (error == boost::asio::error::eof)
                {
                    std::cout << "==> Client closed connection." << std::endl;
                    self->OnCloseSession();
                    return;                 // 不继续监听
                }
            }

            self->Recv();                   // 持续监听数据
        });
}

void Session::Send(const std::string& message) {
    
    m_socket->async_write_some(boost::asio::buffer(message),
        [self = shared_from_this()](const boost::system::error_code& error, std::size_t bytes_transferred) {
            if (!error) 
            {
                std::cout << "==> Sent " << bytes_transferred << " bytes." << std::endl;
            } 
            else 
            {
                std::cerr << "==> Error: " << error.message() << ", errorvalue:" << error.value() << std::endl;
                if (error == boost::asio::error::bad_descriptor)
                {
                    std::cout << "==> in send() Client closed connection." << std::endl;
                    self->OnCloseSession();
                    return;                 // 不继续监听
                }
            }
        }
    );
}

void Session::OnRecv(const char* bufData, size_t len)
{
    std::cout << "==> OnRecv. bufData: " << bufData << std::endl;
}
